package cn.com.bsoft.mobile.ui

import cn.net.xyan.blossom.kotlin.qrCode
import com.github.vok.karibudsl.image
import com.vaadin.server.StreamResource
import com.vaadin.ui.Component
import com.vaadin.ui.UI
import com.vaadin.ui.VerticalLayout
import com.vaadin.ui.Window
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO
import java.io.ByteArrayOutputStream
import java.io.InputStream

internal interface InitPopWindowHandler {
    fun initWindow(w: Window, c: Component)
}

class PopWindow(internal var root: Component) : Window() {

    init {

        val layout = VerticalLayout()
        layout.setMargin(true)
        layout.addComponent(root)

        setSizeUndefined()
        content = layout
    }

}


class QRCodeSource(val qrCodeValue: String) : StreamResource.StreamSource {
    internal var imagebuffer: ByteArrayOutputStream? = null
    internal var reloads = 0

    // This method generates the stream contents
    // Create an image
    // Draw something static
    // Draw something dynamic
    // Write the image to a buffer
    // Return a stream from the buffer
    override fun getStream(): InputStream? {
        val image = qrCodeValue.qrCode
        val output = ByteArrayOutputStream()

        ImageIO.write(image, "png", output)

        return ByteArrayInputStream(output.toByteArray())
    }
}

class QRCodeComponent(val qrCodeValue: String) : VerticalLayout() {
    init {
        val source = QRCodeSource(qrCodeValue)

        val sr = StreamResource(source,"")

        image (null,sr){
            setSizeFull()
        }
        setSizeFull()
    }

    fun show():PopWindow{
        val w = PopWindow(this)
        val ui = UI.getCurrent()
//        if (handler != null)
//            handler.initWindow(w, c)

        ui.addWindow(w)

        return w
    }


}